package com.cnt.controller;

import com.cnt.entity.RequestMoney;
import com.cnt.service.RequestMoneyService;
import com.cnt.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.io.BufferedInputStream;
import java.util.List;

@RequestMapping("/api/funding")
@RestController
public class FundingController {
    @Autowired
    private RequestMoneyService requestMoneyService;
    // 申请拨款接口
    @PostMapping("/apply")
    public ResultVo<String> applyFunding(@RequestBody RequestMoney requestMoney) {
        return requestMoneyService.apply(requestMoney.getDonationId(),requestMoney.getMoney(),requestMoney.getReason());

    }

    @PostMapping("/uploadReport")
    public ResultVo<String> uploadReport(@RequestParam("fundingId") Integer FundingId,
                                         @RequestParam("appropriationFile") MultipartFile file){
        return requestMoneyService.uploadReport(file,FundingId);
    }

    @GetMapping(value = "/downloadReport", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public ResponseEntity<byte[]> downloadReport(@RequestParam("fundingId") Integer fundingId) {
        try (BufferedInputStream bis = new BufferedInputStream(requestMoneyService.downloadReport(fundingId), 4096)) {
            byte[] data = new byte[bis.available()];
            bis.read(data);
            if (data.length == 0) {
                return ResponseEntity.status(500).body(null);
            }
            String safeFileName = "report_" + fundingId + ".pdf";
            return ResponseEntity.ok()
                    .header("Content-Disposition", "attachment; filename=" + safeFileName)
                    .body(data);
        } catch (Exception e) {
            // 处理文件下载失败的情况
            return ResponseEntity.status(500).body(null);
        }
    }

    @GetMapping("/queryByDonationId")
    public ResultVo<List<RequestMoney>> queryByDonationId(@RequestParam Integer donationId, @RequestParam Integer isPerson){
        return requestMoneyService.queryByDonationId(isPerson,donationId);
    }

    @PostMapping("/checkMoney")
    public ResultVo<Double> checkMoney(@RequestBody RequestMoney requestMoney){
        return requestMoneyService.checkMoney(requestMoney.getDonationId());
    }
}
